package com.axend.aerosense.common.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.databinding.DataBindingUtil;

import com.axend.aerosense.base.bean.BaseDevInfoBean;
import com.axend.aerosense.base.utils.EquipmentUtil;
import com.axend.aerosense.common.R;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.UpdateAppBean;
import com.axend.aerosense.common.databinding.CommonCustomUpdateDialogBinding;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.ToastUtils;

import io.reactivex.disposables.Disposable;


public class CustomUpdateDialog extends Dialog {

    private CommonCustomUpdateDialogBinding databinding;
    private boolean isShowTip = false;
    private Disposable disposable;
    private UpdateAppBean updateAppBean;

    public CustomUpdateDialog(Context context, UpdateAppBean updateAppBean, boolean isShowTip) {
        super(context, R.style.Common_CustomDialog);
        this.isShowTip = isShowTip;
        this.updateAppBean = updateAppBean;
        databinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.common_custom_update_dialog, null, false);
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        //设置提示框位置
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        window.setAttributes(lp);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(databinding.getRoot());
        //按空白处不能取消动画
        setCanceledOnTouchOutside(false);
        //初始化界面控件
        initEvent();
        if(null != updateAppBean){
            initView(updateAppBean);

        } else{
            checkUpdate();
        }

    }

    /**
     * 初始化界面的确定和取消监听器
     */
    private void initEvent() {
        //设置更新按钮被点击后，向外界提供监听
        databinding.commonBtnNow.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.axend.aerosense"));
            try{
                getContext().startActivity(intent);
            }catch (Exception e){
                e.printStackTrace();
            }

            if (onClickBottomListener != null) {
                onClickBottomListener.onPositiveClick();
            }
        });
        //设置稍后按钮被点击后，向外界提供监听
        databinding.commonBtnLater.setOnClickListener(v -> {
            dismiss();
            if (onClickBottomListener != null) {
                onClickBottomListener.onNegtiveClick();
            }
        });
        //设置关闭按钮被点击后，向外界提供监听
        databinding.commonClose.setOnClickListener(v -> {
            dismiss();
            if (onClickBottomListener != null) {
                onClickBottomListener.onCloseClick();
            }
        });
    }


    /**
     * 初始化界面控件
     */
    private void initView(UpdateAppBean updateAppBean) {
        String versionCode = "" + EquipmentUtil.getAppVersionNumber();
        if (TextUtils.isEmpty(updateAppBean.getServiceEdtion())
                || Integer.parseInt(versionCode) >= Integer.parseInt(updateAppBean.getServiceEdtion())){
            //不需要更新
            if (isShowTip){
                ToastUtils.showShort(R.string.common_new_version);
            }
        }else {
            //需要更新
            String notice = updateAppBean.getNotice();
            if (null != notice && !TextUtils.isEmpty(notice)){
                String[] textArr = notice.split("/");
                String temp = "";
                for (int i = 0; i < textArr.length; i++){
                    if (i == textArr.length - 1){
                        temp += textArr[i];
                    }else {
                        temp = temp + textArr[i] + "\n\n";
                    }
                }
                databinding.commonNotice.setText(temp);
            }

            if (updateAppBean.getState() == 0){
                //可更新
                databinding.commonBtnLater.setVisibility(View.VISIBLE);
                databinding.commonClose.setVisibility(View.VISIBLE);
            }else if (updateAppBean.getState() == 1){
                //强制更新
                setCancelable(false);
                databinding.commonBtnLater.setVisibility(View.GONE);
                databinding.commonClose.setVisibility(View.GONE);
            }
        }
    }

    public void checkUpdate(){
        disposable = EasyHttp.post(UrlApi.URL.GetAppVersion.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<UpdateAppBean>() {
                    @Override
                    public void onTokenExpire() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        if (disposable != null){
                            disposable.dispose();
                        }
                    }

                    @Override
                    public void onSuccess(UpdateAppBean updateAppBean) {
                        String versionCode = "" + EquipmentUtil.getAppVersionNumber();
                        try {
                            if (TextUtils.isEmpty(updateAppBean.getServiceEdtion())
                                    || Integer.parseInt(versionCode) >= Integer.parseInt(updateAppBean.getServiceEdtion())){
                                //不需要更新
                                if (isShowTip){
                                    ToastUtils.showShort(R.string.common_new_version);
                                }
                            }else {
                                //需要更新
                                show();
                                String notice = updateAppBean.getNotice();
                                if (null != notice && !TextUtils.isEmpty(notice)){
                                    String[] textArr = updateAppBean.getNotice().split("/");
                                    String temp = "";
                                    for (int i = 0; i < textArr.length; i++){
                                        if (i == textArr.length - 1){
                                            temp += textArr[i];
                                        }else {
                                            temp = temp + textArr[i] + "\n\n";
                                        }
                                    }
                                    databinding.commonNotice.setText(temp);
                                }
                                //需要更新
                                if (updateAppBean.getState() == 0){
                                    //可更新
                                    databinding.commonBtnLater.setVisibility(View.VISIBLE);
                                    databinding.commonClose.setVisibility(View.VISIBLE);
                                }else if (updateAppBean.getState() == 1){
                                    setCancelable(false);
                                    //强制更新
                                    databinding.commonBtnLater.setVisibility(View.GONE);
                                    databinding.commonClose.setVisibility(View.GONE);
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if (disposable != null){
                            disposable.dispose();
                        }
                    }
                });
    }

    /**
     * 设置确定取消按钮的回调
     */
    public OnClickBottomListener onClickBottomListener;

    public CustomUpdateDialog setOnClickBottomListener(OnClickBottomListener onClickBottomListener) {
        this.onClickBottomListener = onClickBottomListener;
        return this;
    }

    public interface OnClickBottomListener {
        /**
         * 点击确定按钮事件
         */
        public void onPositiveClick();

        /**
         * 点击取消按钮事件
         */
        public void onNegtiveClick();

        /**
         * 关闭按钮点击事件
         */
        public void onCloseClick();
    }

}
